var filename = ''

const Model = require('../../models/index'),
    Account = Model.Account,
    Collection = Model.Collection,
    express = require('express'),
    router = express.Router(),
    jwt = require('jsonwebtoken'),
    fs = require('fs'),
    crypto = require('crypto'),
    multer = require('multer'),
    mkdirp = require('mkdirp'),
    storage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, 'assets/image')
        },
        filename: (req, file, cb) => {
            let sha1 = crypto.createHash('sha1')
            sha1.update(req.session.account)
            filename = sha1.digest('hex')
            cb(null, req.session.account + '/' + filename + '.png')
        }
    }),
    upload = multer({storage: storage})

router.post('/register', (req, res) => {
    Account.find({account: req.body.account}, (err, data) => {
        if (err) {
            res.send(err)
            return false
        }
        if (data.length) {
            res.send({error_code: 50002, reason: 'account have already registed!', result: 'failed'})
            return false
        }
        let token = jwt.sign({iss: req.body.account, exp: Math.floor(Date.now() / 1000) + 86400000}, 'secret')
        let newAccount = new Account({
            // 返回数据的顺序是由mongoose save时决定的，而不是schema的顺序决定
            account: req.body.account,
            // phone: req.body.phone,
            password: req.body.password
            // memo: req.body.memo,
            // nickname: req.body.nickname,
            // avatar: req.body.avatar |
        })
        newAccount.save((err, account) => {
            if (err) {
                res.send(err)
            } else {
                // 注册成功，创建session, 并将token保存起来
                req.session.regenerate(function (err) {
                    if (err) { res.send('register failed'); return }
                    // init collection
                    req.session.token = token

                    let collection = new Collection({
                        account: req.body.account
                    })
                    collection.save((err) => {
                        if (err) {
                            // todo change code
                            res.send({error_code: 503, reason: 'when save collection', result: 'failed'})
                        } else {
                            res.send({result: 'success', token: token, account: account[0]})
                        }
                    })
                })
            }
        })
    })
})

router.post('/login', (req, res) => {
    Account.find({account: req.body.account}, (err, data) => {
        if (err) {
            res.send({error_code: 503, reason: 'when find account', result: 'failed'})
            return false
        }
        if (!data.length) {
            res.send({error_code: 50001, reason: "account haven't registed yet !", result: 'failed'})
            return false
        }
        Account.find({account: req.body.account, password: req.body.password}, (err, data) => {
            if (err) {
                res.send({error_code: 503, reason: 'when find account & password', result: 'failed'})
                return false
            }
            if (!data.length) {
                res.send({error_code: 50003, reason: 'password error', result: 'failed'})
                return false
            }
            // 创建用户文件夹
            if (!fs.existsSync('assets/image/' + req.body.account)) {
                mkdirp('assets/image/' + req.body.account + '/artical', (err) => {
                    // change code
                    if (err) {
                        res.send({error_code: 503, reason: 'when mkdir', result: 'failed'})
                    }
                })
            }
            // 生成token并存入session
            let token = jwt.sign({iss: req.body.account, exp: Math.floor(Date.now() / 1000) + 86400000}, 'secret')
            req.session.regenerate(function (err) {
                if (err) { res.send('login failed'); return }

                req.session.token = token
                res.send({result: 'success', token: token, account: data[0]})
            })
        })
    })
})

router.put('/logout', (req, res) => {
    Account.deleteOne({account: req.body.account}, (err) => {
        if (err) {
            res.send({error_code: 504, reason: 'when delete session', result: 'failed'})
        } else {
            req.session.destroy(function (err) {
                if (err) { res.send('loginout failed'); return }
                res.send({result: 'success'})
            })
        }
    })
})

router.get('/basic', (req, res) => {
    Account.find({account: req.session.account}, '-_id', (err, data) => {
        if (err) {
            res.send({error_code: 503, reason: 'when find user basic info', result: 'failed'})
        } else {
            res.send({result: 'success', data: data[0]})
        }
    })
})

router.get('/friend/all', (req, res) => {
    Account.find({account: req.session.account}, 'friend -_id', (err, data) => {
        if (err) {
            res.send({error_code: 503, reason: 'when find all friends', result: 'failed'})
        } else {
            res.send({result: 'success', data: data})
        }
    })
})
// fs.mkdirSync('test')
// todo
router.post('/avatar', upload.single('avatar'), (req, res) => {
    let avatarPath = `assets/image/${req.session.account}/${filename}.png`
    Account.findOneAndUpdate({account: req.session.account}, {avatar: avatarPath}, (err, data) => {
        if (err) {
            res.send({error_code: 503, reason: 'when find account', result: 'failed'})
        } else {
            res.send({result: 'success', avatarpath: avatarPath})
        }
    })
})

module.exports = router
